package com.nit.tools.easy;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.nit.enums.OSEnum;
import com.nit.tools.OSUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 *
 */
@Slf4j
public class ConvertWordToPDF {

    public void convert(String wordPath, String pdfPath) {
        OSEnum osEnum = OSEnum.getOSEnum();
        switch (osEnum) {
            case WIN:
                documents4jWordToPdf(wordPath, pdfPath);
                break;
            case LINUX:
                linuxDocuments4jWordToPdf(new File(wordPath));
                break;
            default:
                linuxDocuments4jWordToPdf(new File(wordPath));
                break;
        }
    }

    private void documents4jWordToPdf(String sourcePath, String targetPath) {
        File inputWord = new File(sourcePath);
        File outputFile = new File(targetPath);
        try {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            boolean execute = converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).schedule().get();
            outputStream.close();
            docxInputStream.close();

            log.info("转换完毕 targetPath = {}", outputFile.getAbsolutePath());
            System.out.println("转换完毕 targetPath = " + outputFile.getAbsolutePath());
            converter.shutDown();
            return;
        } catch (Exception e) {
            log.error("[documents4J] word转pdf失败:{}", e.toString());
        }
    }

    private File linuxDocuments4jWordToPdf(File file) {
        // 获取文件的绝对路径和目录路径
        String absolutePath = file.getAbsolutePath();
        String parentPath = file.getParent();

        // 构建LibreOffice的命令行工具命令
        String commands = "libreoffice --convert-to pdf " + absolutePath + " --outdir " + parentPath;
        // 执行转换命令
        try {
            boolean result = executeLinuxCmd(commands);
            if (result) {
                // 转换成功，返回转换后的PDF文件
                String pdfFilePath = parentPath + File.separator + file.getName().replaceAll("\\.(docx?|\\w+)$", "") + ".pdf";
                log.info(pdfFilePath);
                log.info(pdfFilePath);
                return new File(pdfFilePath);
            } else {
                return null;
            }

        } catch (Exception e) {
            // 转换失败
            e.printStackTrace();
            log.error("Word文档转换为PDF失败，原因：执行命令时出现异常。", e);
            return null;
        }
    }

    private boolean executeLinuxCmd(String cmd) throws IOException {
        // 执行命令行工具命令
        Process process = Runtime.getRuntime().exec(cmd);
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            log.error("执行 Linux 命令异常：", e);
            return false;
        }
        return true;
    }
}
